import React, {useState} from 'react';
import {Alert, Button, Card, Form, Input, message, Typography} from 'antd';
import {history, Link, useModel} from '@umijs/max';
import {register, login} from '@/services/ant-design-pro/userController';
import {LockOutlined, MailOutlined, PhoneOutlined, UserOutlined} from '@ant-design/icons';
import styles from './index.less';
import { saveUserAuth } from '@/utils/auth';

const {Title, Paragraph} = Typography;

// 注册错误提示组件
const RegisterMessage: React.FC<{
  content: string;
}> = ({content}) => (
  <div>
    <div style={{ color: 'red' }}>{content}</div>
  </div>
);

const Register: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>('');
  // [MOD] 添加全局状态管理，用于自动登录
  const {setInitialState} = useModel('@@initialState');

  const handleSubmit = async (values: API.UserRegisterDTO) => {
    setLoading(true);
    setError('');
    try {
      // 校验密码是否一致
      if (values.password !== values.confirmPassword) {
        setError('两次输入的密码不匹配!');
        setLoading(false);
        return;
      }

      // 调用注册API
      const res = await register(values);

      // [MOD] 优化错误处理，显示后端返回的具体错误信息
      if (res.code === 0) {
        // [MOD] 注册成功后自动登录用户
        try {
          // 登录获取token
          const loginRes = await login({
            account: values.account,
            password: values.password,
          });

          if (loginRes && loginRes.code === 0 && loginRes.data) {
            // 保存登录凭证
            if (loginRes.data.token) {
              saveUserAuth(loginRes.data, loginRes.data.token);
            }

            // 更新全局用户状态
            await setInitialState((oldInitialState) => {
              return {
                ...oldInitialState,
                currentUser: loginRes.data,
              };
            });

            // 不再自动创建聊天会话，将在用户发送第一条消息时创建
            console.log('注册成功，将在发送第一条消息时创建聊天');

            // 显示注册成功消息
            message.success('注册成功！正在跳转到聊天页面...');

            // [MOD] 直接跳转到聊天页面，而不是登录页
            window.location.href = '/chat';
            return;
          } else {
            // 登录失败，仍然跳转到登录页
            message.success('注册成功！请登录');
            history.push('/user/login');
          }
        } catch (error) {
          // 自动登录失败，跳转到登录页
          console.error('注册后自动登录失败:', error);
          message.success('注册成功！请登录');
          history.push('/user/login');
        }
      } else {
        // [MOD] 显示后端返回的详细错误信息
        const errorMsg = res.message || '注册失败，请重试';
        setError(errorMsg);
        message.error(errorMsg);
      }
    } catch (error: any) {
      // [MOD] 捕获并显示请求异常中的错误信息
      const errorMsg = error.message || error.info?.errorMessage || '注册失败，请稍后再试';
      setError(errorMsg);
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <Title level={2}>AI 聊天平台</Title>
          <Paragraph>注册新账号</Paragraph>
        </div>

        <Card className={styles.card}>
          {/* 错误提示 */}
          {error && <RegisterMessage content={error} />}

          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="account"
              rules={[{required: true, message: '请输入账号'}]}
            >
              <Input
                prefix={<UserOutlined/>}
                placeholder="账号"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="username"
              rules={[{required: true, message: '请输入用户名'}]}
            >
              <Input
                prefix={<UserOutlined/>}
                placeholder="用户名"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{required: true, message: '请输入密码'}]}
            >
              <Input.Password
                prefix={<LockOutlined/>}
                placeholder="密码"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              rules={[
                {required: true, message: '请确认密码'},
                ({getFieldValue}) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password
                prefix={<LockOutlined/>}
                placeholder="确认密码"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                {required: false},
                {type: 'email', message: '请输入有效的邮箱地址'},
              ]}
            >
              <Input
                prefix={<MailOutlined/>}
                placeholder="邮箱（选填）"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="phone"
              rules={[{required: false}]}
            >
              <Input
                prefix={<PhoneOutlined/>}
                placeholder="手机号（选填）"
                size="large"
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={loading}
                size="large"
              >
                注册
              </Button>
            </Form.Item>
          </Form>

          <div className={styles.actions}>
            <Link to="/user/login">已有账号？立即登录</Link>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Register;
